package org.phytodata.actionengine;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.util.beans.ActionHarness;

/* replace this with a JAX-RS WS that returns JSON like this (see executor.groovy):
{
  executionResult: "${escape(result)}",
  outputText: "${escape(stream.toString(encoding))}",
  stacktraceText: "${escape(stacktrace)}"
}
*/
public class GroovyConsoleServlet extends HttpServlet {
  
  private static final long serialVersionUID = 1584486522001535135L;
  private static final Log log = LogFactory.getLog(GroovyConsoleServlet.class);

  @SuppressWarnings("nls")
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String scriptText = req.getParameter("script");
    if(scriptText == null) {
      log.error("No Script requested");
    }
      
    GroovyEngineAction action = new GroovyEngineAction();
    ActionHarness harness = new ActionHarness(action);
    
    @SuppressWarnings("unchecked")
    Map<String, Object> inputMap = new HashMap<String, Object>(req.getParameterMap());
    inputMap.put("scriptText", scriptText);
    
    //because we are in a request, pass the session on to the script as well
    inputMap.put("session", PentahoSessionHolder.getSession());
    
    try {
      harness.setValues(inputMap);
      action.execute();
    } catch (Exception e) {
      log.error("GroovyEngineServlet failed to execute script", e);
      resp.sendError(500, "GroovyEngineServlet failed to execute script: "+e.getMessage()+" See log for more details");
    }
  }
  

}
